<template>
  <div class="realtime-alarm-container">
    <el-row :gutter="20">
      <!-- 左侧：实时报警列表 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>实时报警列表</span>
              <el-button type="primary" size="small" @click="refreshAlarms">刷新</el-button>
            </div>
          </template>
          
          <el-table 
            :data="alarmList" 
            style="width: 100%" 
            v-loading="loading"
            :row-class-name="getRowClassName"
            @row-click="handleRowClick"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="alarmCode" label="报警编码" width="150" />
            <el-table-column prop="sourceName" label="报警来源" width="120" />
            <el-table-column prop="alarmType" label="报警类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getAlarmTypeTag(row.alarmType)">
                  {{ getAlarmTypeName(row.alarmType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alarmLevel" label="报警级别" width="100">
              <template #default="{ row }">
                <el-tag :type="getAlarmLevelTag(row.alarmLevel)" :effect="row.alarmLevel === 1 ? 'dark' : 'plain'">
                  {{ getAlarmLevelName(row.alarmLevel) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alarmContent" label="报警内容" show-overflow-tooltip />
            <el-table-column prop="triggerTime" label="触发时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.triggerTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">
                  {{ getStatusName(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleDetail(row)">详情</el-button>
                <el-button type="warning" size="small" @click="handlePush(row)">推送</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <!-- 右侧：地图和辅助信息 -->
      <el-col :span="8">
        <!-- 报警级别说明 -->
        <el-card class="mb-20">
          <template #header>
            <span>报警级别说明</span>
          </template>
          <div class="level-info">
            <div class="level-item level-urgent">
              <span class="level-dot"></span>
              <span>紧急：红色标识，需1小时内处理</span>
            </div>
            <div class="level-item level-important">
              <span class="level-dot"></span>
              <span>重要：橙色标识，需4小时内处理</span>
            </div>
            <div class="level-item level-normal">
              <span class="level-dot"></span>
              <span>一般：蓝色标识，需24小时内处理</span>
            </div>
          </div>
        </el-card>
        
        <!-- 常用操作 -->
        <el-card class="mb-20">
          <template #header>
            <span>常用操作</span>
          </template>
          <div class="action-buttons">
            <el-button type="primary" @click="handleBatchExport">批量导出</el-button>
            <el-button type="success" @click="handleBatchAssign">一键派单</el-button>
            <el-button type="warning" @click="handleAlarmUpgrade">报警升级</el-button>
          </div>
        </el-card>
        
        <!-- 高频报警点TOP5 -->
        <el-card>
          <template #header>
            <span>高频报警点TOP5</span>
          </template>
          <el-scrollbar height="300px">
            <div 
              v-for="(point, index) in topAlarmPoints" 
              :key="index"
              class="top-point-item"
              @click="handlePointClick(point)">
              <div class="point-rank">{{ index + 1 }}</div>
              <div class="point-info">
                <div class="point-name">{{ point.sourceName }}</div>
                <div class="point-count">报警次数: {{ point.alarmCount }}</div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 一键派单 -->
    <el-dialog 
      v-model="batchAssignDialogVisible" 
      title="一键派单" 
      width="520px"
      :close-on-click-modal="false">
      <el-form 
        :model="batchAssignForm" 
        :rules="batchAssignRules" 
        ref="batchAssignFormRef"
        label-width="100px">
        <el-form-item label="已选报警">
          <span>{{ selectedRows.length }} 条</span>
        </el-form-item>
        <el-form-item label="接收人" prop="userIds">
          <el-select 
            v-model="batchAssignForm.userIds" 
            multiple 
            filterable 
            placeholder="请选择接收人"
            style="width: 100%">
            <el-option 
              v-for="user in userOptions" 
              :key="user.id" 
              :label="user.name" 
              :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="推送渠道" prop="channels">
          <el-checkbox-group v-model="batchAssignForm.channels">
            <el-checkbox 
              v-for="item in channelOptions" 
              :key="item.value" 
              :label="item.value">
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="batchAssignForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="可选，填写派单说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchAssignDialogVisible = false" :disabled="batchAssignLoading">取 消</el-button>
        <el-button type="primary" @click="submitBatchAssign" :loading="batchAssignLoading">确认派单</el-button>
      </template>
    </el-dialog>

    <!-- 报警升级 -->
    <el-dialog 
      v-model="upgradeDialogVisible" 
      title="报警升级" 
      width="520px"
      :close-on-click-modal="false">
      <el-form 
        :model="upgradeForm" 
        :rules="upgradeRules" 
        ref="upgradeFormRef"
        label-width="100px">
        <el-form-item label="已选报警">
          <span>{{ selectedRows.length }} 条</span>
        </el-form-item>
        <el-form-item label="责任人" prop="handlerId">
          <el-select 
            v-model="upgradeForm.handlerId" 
            placeholder="请选择责任人"
            style="width: 100%">
            <el-option 
              v-for="handler in handlerOptions" 
              :key="handler.id" 
              :label="handler.name" 
              :value="handler.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="升级原因" prop="reason">
          <el-input 
            v-model="upgradeForm.reason" 
            type="textarea" 
            :rows="3"
            placeholder="请输入升级原因" />
        </el-form-item>
        <el-form-item label="升级措施" prop="measure">
          <el-input 
            v-model="upgradeForm.measure" 
            type="textarea" 
            :rows="3"
            placeholder="请输入后续处理措施或建议" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="upgradeDialogVisible = false" :disabled="upgradeLoading">取 消</el-button>
        <el-button type="primary" @click="submitAlarmUpgrade" :loading="upgradeLoading">确认升级</el-button>
      </template>
    </el-dialog>

    <!-- 报警详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="报警详情" width="60%">
      <AlarmDetail :alarm-id="currentAlarmId" v-if="detailDialogVisible" />
    </el-dialog>
    
    <!-- 推送弹窗 -->
    <el-dialog v-model="pushDialogVisible" title="推送报警" width="50%">
      <PushAlarm :alarm-id="currentAlarmId" @success="handlePushSuccess" v-if="pushDialogVisible" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getRealtimeAlarms, 
  getHighFreqPoints, 
  exportRealtimeAlarmData,
  pushAlarm,
  handleAlarm
} from '@/api/prod_operate/alarm_management'
import AlarmDetail from './AlarmDetail.vue'
import PushAlarm from './PushAlarm.vue'

const loading = ref(false)
const alarmList = ref([])
const topAlarmPoints = ref([])
const selectedRows = ref([])
const detailDialogVisible = ref(false)
const pushDialogVisible = ref(false)
const batchAssignDialogVisible = ref(false)
const upgradeDialogVisible = ref(false)
const currentAlarmId = ref(null)
const batchAssignFormRef = ref(null)
const upgradeFormRef = ref(null)
const batchAssignLoading = ref(false)
const upgradeLoading = ref(false)
let refreshTimer = null

const userOptions = ref([
  { id: 'user001', name: '运维主管' },
  { id: 'user002', name: '现场工程师A' },
  { id: 'user003', name: '现场工程师B' }
])

const handlerOptions = ref([
  { id: 'current_user', name: '当前用户' },
  { id: 'user001', name: '运维主管' },
  { id: 'user002', name: '现场工程师A' },
  { id: 'user003', name: '现场工程师B' }
])

const channelOptions = [
  { label: '短信', value: 1 },
  { label: 'APP', value: 2 },
  { label: '站内信', value: 3 },
  { label: '系统弹窗', value: 4 }
]

const batchAssignForm = ref({
  userIds: [],
  channels: [],
  remark: ''
})

const upgradeForm = ref({
  handlerId: 'current_user',
  reason: '',
  measure: ''
})

const batchAssignRules = {
  userIds: [{ required: true, message: '请选择接收人', trigger: 'change' }],
  channels: [{ required: true, message: '请选择推送渠道', trigger: 'change' }]
}

const upgradeRules = {
  handlerId: [{ required: true, message: '请选择责任人', trigger: 'change' }],
  reason: [{ required: true, message: '请输入升级原因', trigger: 'blur' }],
  measure: [{ required: true, message: '请输入升级措施', trigger: 'blur' }]
}

const resetBatchAssignForm = () => {
  batchAssignForm.value.userIds = []
  batchAssignForm.value.channels = []
  batchAssignForm.value.remark = ''
  if (batchAssignFormRef.value) {
    batchAssignFormRef.value.clearValidate()
  }
}

const resetUpgradeForm = () => {
  upgradeForm.value.handlerId = 'current_user'
  upgradeForm.value.reason = ''
  upgradeForm.value.measure = ''
  if (upgradeFormRef.value) {
    upgradeFormRef.value.clearValidate()
  }
}

const ensureSelection = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先勾选至少一条报警')
    return false
  }
  return true
}

const getFileName = (prefix) => {
  const now = new Date()
  const pad = (num) => num.toString().padStart(2, '0')
  return `${prefix}_${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.xlsx`
}

const downloadExcel = async (data, fileName) => {
  if (!data) {
    ElMessage.error('导出失败：返回数据为空')
    return
  }
  const blob = data instanceof Blob ? data : new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  if (blob.type === 'application/json') {
    const text = await blob.text()
    try {
      const err = JSON.parse(text)
      ElMessage.error(err.msg || '导出失败')
    } catch (error) {
      ElMessage.error('导出失败')
    }
    return
  }
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

// 获取实时报警列表
const fetchRealtimeAlarms = async () => {
  loading.value = true
  try {
    const res = await getRealtimeAlarms()
    if (res.code === 200) {
      alarmList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const normalizeTopAlarmPoints = (list = []) => {
  if (!Array.isArray(list)) return []
  return list.map(item => {
    const sourceId =
      item.sourceId ??
      item.highFreqPointId ??
      item.high_freq_point_id ??
      item.source_id ??
      null
    const sourceName =
      item.sourceName ??
      item.highFreqPointName ??
      item.high_freq_point_name ??
      '未知报警点'
    const countRaw =
      item.alarmCount ??
      item.highFreqCount ??
      item.high_freq_count ??
      0
    const alarmCount = Number.isFinite(Number(countRaw)) ? Number(countRaw) : 0
    return {
      ...item,
      sourceId,
      sourceName,
      alarmCount: alarmCount < 0 ? 0 : alarmCount
    }
  })
}

// 获取高频报警点
const fetchTopAlarmPoints = async () => {
  try {
    const res = await getHighFreqPoints(5)
    if (res.code === 200) {
      topAlarmPoints.value = normalizeTopAlarmPoints(res.data)
    }
  } catch (error) {
    console.error('获取高频报警点失败：', error)
  }
}

// 刷新报警列表
const refreshAlarms = () => {
  fetchRealtimeAlarms()
  fetchTopAlarmPoints()
}

// 行样式
const getRowClassName = ({ row }) => {
  if (row.alarmLevel === 1) {
    return 'alarm-row-urgent'
  } else if (row.alarmLevel === 2) {
    return 'alarm-row-important'
  } else {
    return 'alarm-row-normal'
  }
}

// 行点击
const handleRowClick = (row) => {
  handleDetail(row)
}

// 查看详情
const handleDetail = (row) => {
  currentAlarmId.value = row.id
  detailDialogVisible.value = true
}

// 推送报警
const handlePush = (row) => {
  currentAlarmId.value = row.id
  pushDialogVisible.value = true
}

// 推送成功回调
const handlePushSuccess = () => {
  pushDialogVisible.value = false
  refreshAlarms()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 批量导出
const handleBatchExport = async () => {
  try {
    if (!alarmList.value.length) {
      ElMessage.warning('暂无报警数据可导出')
      return
    }
    const rowsToExport = selectedRows.value.length > 0 ? selectedRows.value : alarmList.value
    const alarmIds = rowsToExport.map(item => item.id)
    const res = await exportRealtimeAlarmData({ alarmIds })
    await downloadExcel(res, getFileName('实时报警数据'))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败：' + error.message)
  }
}

// 一键派单
const handleBatchAssign = () => {
  if (!ensureSelection()) return
  resetBatchAssignForm()
  batchAssignDialogVisible.value = true
}

const submitBatchAssign = async () => {
  if (!batchAssignFormRef.value) return
  try {
    await batchAssignFormRef.value.validate()
  } catch (error) {
    return
  }

  const alarmIds = selectedRows.value.map(item => item.id).filter(Boolean)
  if (!alarmIds.length) {
    ElMessage.warning('所选报警缺少有效ID')
    return
  }

  batchAssignLoading.value = true
  try {
    const payload = {
      userIds: [...batchAssignForm.value.userIds],
      channels: [...batchAssignForm.value.channels],
      remark: batchAssignForm.value.remark || ''
    }
    const results = await Promise.allSettled(
      alarmIds.map(alarmId => pushAlarm({ alarmId, ...payload }))
    )
    const failedAlarms = results
      .map((result, index) => {
        if (result.status === 'fulfilled') {
          return result.value.code === 200 ? null : alarmIds[index]
        }
        return alarmIds[index]
      })
      .filter(Boolean)

    if (failedAlarms.length === 0) {
      ElMessage.success(`成功派单 ${alarmIds.length} 条报警`)
      batchAssignDialogVisible.value = false
      refreshAlarms()
    } else {
      ElMessage.error(`有 ${failedAlarms.length} 条报警派单失败`)
    }
  } catch (error) {
    ElMessage.error('派单失败：' + error.message)
  } finally {
    batchAssignLoading.value = false
  }
}

// 报警升级
const handleAlarmUpgrade = () => {
  if (!ensureSelection()) return
  resetUpgradeForm()
  upgradeDialogVisible.value = true
}

const submitAlarmUpgrade = async () => {
  if (!upgradeFormRef.value) return
  try {
    await upgradeFormRef.value.validate()
  } catch (error) {
    return
  }

  const alarmIds = selectedRows.value.map(item => item.id).filter(Boolean)
  if (!alarmIds.length) {
    ElMessage.warning('所选报警缺少有效ID')
    return
  }

  upgradeLoading.value = true
  try {
    const payload = {
      handlerId: upgradeForm.value.handlerId,
      reasonAnalysis: upgradeForm.value.reason,
      handleMeasure: upgradeForm.value.measure,
      handleResult: 3
    }

    const results = await Promise.allSettled(
      alarmIds.map(alarmId => handleAlarm({ ...payload, alarmId }))
    )

    const failedAlarms = results
      .map((result, index) => {
        if (result.status === 'fulfilled') {
          return result.value.code === 200 ? null : alarmIds[index]
        }
        return alarmIds[index]
      })
      .filter(Boolean)

    if (failedAlarms.length === 0) {
      ElMessage.success(`成功升级 ${alarmIds.length} 条报警`)
      upgradeDialogVisible.value = false
      refreshAlarms()
    } else {
      ElMessage.error(`有 ${failedAlarms.length} 条报警升级失败`)
    }
  } catch (error) {
    ElMessage.error('报警升级失败：' + error.message)
  } finally {
    upgradeLoading.value = false
  }
}

// 点击高频报警点
const handlePointClick = (point) => {
  ElMessage.info(`查看 ${point.sourceName} 的报警详情`)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取报警类型标签
const getAlarmTypeTag = (type) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[type] || 'info'
}

// 获取报警类型名称
const getAlarmTypeName = (type) => {
  const map = { 1: '设备故障', 2: '参数超标', 3: '通讯中断' }
  return map[type] || '未知'
}

// 获取报警级别标签
const getAlarmLevelTag = (level) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[level] || 'info'
}

// 获取报警级别名称
const getAlarmLevelName = (level) => {
  const map = { 1: '紧急', 2: '重要', 3: '一般' }
  return map[level] || '未知'
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = { 
    1: 'info', 
    2: 'warning', 
    3: 'warning', 
    4: 'primary', 
    5: 'success', 
    6: 'danger' 
  }
  return map[status] || 'info'
}

// 获取状态名称
const getStatusName = (status) => {
  const map = { 
    1: '未推送', 
    2: '已推送未接收', 
    3: '已接收待处理', 
    4: '处理中', 
    5: '已闭环', 
    6: '已驳回' 
  }
  return map[status] || '未知'
}

onMounted(() => {
  fetchRealtimeAlarms()
  fetchTopAlarmPoints()
  // 每30秒自动刷新
  refreshTimer = setInterval(() => {
    fetchRealtimeAlarms()
  }, 30000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.realtime-alarm-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 报警行样式 */
:deep(.alarm-row-urgent) {
  background-color: #fef0f0;
  animation: blink 2s infinite;
}

:deep(.alarm-row-important) {
  background-color: #fdf6ec;
  animation: blink 1s infinite;
}

:deep(.alarm-row-normal) {
  background-color: #f0f9ff;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

/* 报警级别说明 */
.level-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.level-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.level-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
}

.level-urgent .level-dot {
  background-color: #f56c6c;
}

.level-important .level-dot {
  background-color: #e6a23c;
}

.level-normal .level-dot {
  background-color: #409eff;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-buttons .el-button {
  width: 100%;
}

/* 高频报警点 */
.top-point-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.top-point-item:hover {
  background-color: #f5f7fa;
}

.point-rank {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  margin-right: 10px;
  font-weight: bold;
}

.point-info {
  flex: 1;
}

.point-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.point-count {
  font-size: 12px;
  color: #909399;
}
</style>

